package socket;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Server {
    private ServerSocket serverSocket;//总机
    //private List<PrintWriter> allOut = new ArrayList<>();//设计集合存放所有客户端输出流，用于群发消息
    private Map<String,PrintWriter> allOut = new HashMap<>();
    public Server(){
        try {
            System.out.println("正在启动服务器");
            serverSocket = new ServerSocket(8088);
            System.out.println("服务器启动完毕");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 用于启动服务器程序的执行
     */
    public void start(){
        try {
            while(true){
                System.out.println("等待与客户端连接..");
                Socket socket = serverSocket.accept();
                System.out.println("一个客户端连接了！");
                //启动一个线程来处理该客户端的交互
                ClientHandler handler = new ClientHandler(socket);
                Thread t = new Thread(handler);
                t.start();
            }

        } catch (Exception e) {
        }
    }

    public static void main(String[] args) {
        Server server = new Server();
        server.start();

    }

    /**
     * 该线程任务用于负责与指定的客户端交互
     */
    private class ClientHandler implements Runnable{
        private Socket socket;
        private String host; //记录该客户端的IP地址
        private String nickName; //记录客户端昵称
        public ClientHandler(Socket socket){
            this.socket = socket;
            host = socket.getInetAddress().getHostAddress();
        }
        public void run(){
            PrintWriter pw = null;
            try {
                //通过socket获取输入流用于读取客户端发来的消息
                InputStream in = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(in, StandardCharsets.UTF_8);
                BufferedReader br = new BufferedReader(isr);

                //通过socket获取输出流用于向客户端发送消息
                OutputStream out = socket.getOutputStream();
                OutputStreamWriter osw = new OutputStreamWriter(out,StandardCharsets.UTF_8);
                BufferedWriter bw = new BufferedWriter(osw);
                pw = new PrintWriter(bw,true);

                nickName = br.readLine(); //读取客户端发送过来的昵称

                synchronized (allOut){
                    allOut.put(nickName,pw);//将客户端输出流存入共享群聊集合中
                }
                sendMessageToAll("上线了，当前在线人数:"+allOut.size());

                String message;
                while ((message=br.readLine())!=null){//读取客户端发来的消息
                    if (message.startsWith("@")){//私聊
                        sendMessageToSomeone(message);
                    }else {//群聊
                        sendMessageToAll("说:"+message);
                    }
                }
            } catch (IOException e) {
            }finally {
                synchronized (allOut){
                allOut.remove(nickName);} //将该客户端的输出流从共享集合中删除
                sendMessageToAll("下线了，当前在线人数:"+allOut.size());
                try {
                    socket.close();
                } catch (IOException e) {
                }
            }

        }
        /**
         * 将消息发送给所有客户端(群聊)
         */
        private void sendMessageToAll(String message){
            System.out.println(nickName+"["+host+"]"+message);
            synchronized (allOut) {
                for (PrintWriter o : allOut.values()) {
                    o.println(nickName + "[" + host + "]" + message);
                }
            }
        }
        /**
         * 将消息发给指定用户（私聊）
         */
        private  void sendMessageToSomeone(String message){
            if (message.matches("@.+:.+")){//验证私聊格式是否合适
                String toNickName = message.substring(1,message.indexOf(":"));//提取对方昵称
                if (allOut.containsKey(toNickName)){//在线
                    PrintWriter pw = allOut.get(toNickName);
                    //截取私聊内容
                    String toMessage = message.substring(message.indexOf(":")+1);
                    pw.println(nickName+"悄悄对你说"+toMessage);
                }else {//不在线
                    PrintWriter pw = allOut.get(nickName);//根据昵称获取当前客户端的输出流
                    pw.println("该用户["+toNickName+"]不在线！");
                }
            }else {//格式不正确，通知当前用户格式不对
                PrintWriter pw = allOut.get(nickName);
                pw.println("私聊格式不正确！");

            }
        }

    }
}
